import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'work_item.dart';

GlobalKey<_ScrollListState> scrollListKey = GlobalKey();

class ScrollList extends StatefulWidget {
  final Function req;
  final Function(int index, Object any) childFun;
  ScrollList({Key? key, required this.req, required this.childFun})
      : super(key: key);

  @override
  _ScrollListState createState() => _ScrollListState();
}

class _ScrollListState extends State<ScrollList> {
  final ScrollController _controller = ScrollController();
  final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =
      new GlobalKey<RefreshIndicatorState>();
  bool isLoading = false;
  List<String> data = [];

  fetchData({bool isRefresh: false}) async {
    await Future.delayed(Duration(seconds: 2));
    final temp = await widget.req();
    if (isRefresh) {
      data.clear();
    }
    data.addAll(temp);
    isLoading = false;
    if (!mounted) {
      return;
    }
    setState(() {});
    if (isRefresh) {
      Future.delayed(Duration.zero, () {
        _controller.jumpTo(0);
      });
    }
  }

  handleRefresh() {
    _refreshIndicatorKey.currentState?.show();
  }

  @override
  void initState() {
    super.initState();
    fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return data.isEmpty
        ? Center(
            child: CupertinoActivityIndicator(),
          )
        : Scrollbar(
            child: RefreshIndicator(
                key: _refreshIndicatorKey,
                strokeWidth: 3,
                color: Colors.red,
                backgroundColor: Colors.black,
                onRefresh: () async {
                  await fetchData(isRefresh: true);
                  setState(() {});
                },
                child: NotificationListener(
                  onNotification: (ScrollNotification event) {
                    if (event.metrics.maxScrollExtent <=
                            _controller.offset + 100 &&
                        !isLoading) {
                      //表示距离底部100的时候
                      isLoading = true;
                      fetchData();
                    }
                    return false; //表示继续向上冒泡
                  },
                  child: ListView.builder(
                      // 预加载空间为0
                      cacheExtent: 0,
                      controller: _controller,
                      itemCount: data.length + 1,
                      itemBuilder: (_, index) {
                        if (index == data.length) {
                          return Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              CupertinoActivityIndicator(),
                              Text('正在加载...')
                            ],
                          );
                        }
                        return WorkItem(
                          bean: data[index],
                          index: index,
                          childFun: widget.childFun,
                        );
                      }),
                )));
  }
}
